import { login, getUserInfo, getUserInfoById } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    setUserInfo: {}
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      setToken(token)
      localStorage.setItem('loginTime', Date.now())
    },
    setUserInfo(state, data) {
      state.setUserInfo = data
      console.log('state.setUserInfo', state.setUserInfo)
    },
    removeToken(state) {
      // 清除token
      state.token = null
      // 清除cookic中的token
      removeToken()
      // 清除用户数据
      state.setUserInfo = {}
    },
    removeTokenIfon(state) {
      state.setUserInfo = {}
    }
  },
  actions: {
    async login(store, data) {
      const res = await login(data)
      store.commit('SET_TOKEN', res)
    },
    async getUserInfo(store) {
      const res = await getUserInfo()
      const result = await getUserInfoById(res.userId)
      store.commit('setUserInfo', res)
      store.commit('setUserInfo', { ...res, ...result })
    },
    logout(store) {
      store.commit('removeToken')
      // store.commit('removeTokenInfo')
    }
  }
}
